import router from './router'
import store from './store'
import {
  Message
} from 'element-ui'
import NProgress from 'nprogress' // progress bar进度条
import 'nprogress/nprogress.css' // progress bar style
import {
  getToken
} from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import {
  getAsyncRoutes
} from '@/router/asyncRouter' //动态路由
NProgress.configure({
  showSpinner: false
}) // NProgress Configuration NProgress配置
const whiteList = ['/login'] // no redirect whitelist 无重定向白名单

if (store.state.user.routes) {

  const accessRoutes = getAsyncRoutes(store.state.user.routes);
  router.addRoutes(accessRoutes);
  global.antRouter = accessRoutes
}
// 路由拦截器
router.beforeEach(async (to, from, next) => {
  // console.log('to',to)
  // console.log('from',from)
  // console.log('next',next)
  // 进度条加载
  NProgress.start()

  // 获取page标题
  document.title = getPageTitle(to.meta.title)

  // 获取token决定用户是否可以登录
  const hasToken = getToken()
  // console.log("hasToken", hasToken);
  if (hasToken) { // 判断是否有token
    if (to.path === '/login') {
      //如果已登录，则重定向到主页
      next({
        path: '/'
      })
      NProgress.done()
    } else {

      next();
    }
  } else {
    /* 没有token */
    if (whiteList.indexOf(to.path) !== -1) {
      // 如果该路由在白名单内, 放行
      next()
    } else {
      // 不在白名单内不允许通过重定向到登录页
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})
router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
